package com.jianchi.fsp.appui;

import android.content.Context;
import android.content.SharedPreferences;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by fsp on 16-5-21.
 */
public class HistoryManager {
    Context context;
    List<History> histories;
    SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public HistoryManager(Context _c){
        context=_c;
        histories=new LinkedList<>();
        init();
    }

    public void addHistory(String appName, String picUrl){
        History n = null;
        for(History h : histories){
            if(h.appName.equals(appName)){
                n=h;
                break;
            }
        }
        if(n!=null){
            histories.remove(n);
            n.viewTime=new Date();
            histories.add(n);
        }
        else {
            if(histories.size()>=10){
                histories.remove(0);
            }
            n=new History();
            n.viewTime=new Date();
            n.picUrl=picUrl;
            n.appName=appName;
            histories.add(n);
        }
        save();
    }

    void init(){
        SharedPreferences sp = context.getSharedPreferences("histories", Context.MODE_PRIVATE);
        String s = sp.getString("histories", "");

        String[] ss = s.split(",");
        for(String hs : ss){
            if(!hs.isEmpty()) {
                String hss[] = hs.split(";");
                History h = new History();
                h.appName=hss[0];
                h.picUrl=hss[1];
                try {
                    h.viewTime=fmt.parse(hss[2]);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                histories.add(h);
            }
        }
    }

    public void save(){

        StringBuffer sb = new StringBuffer();
        for(History h : histories){
            sb.append(h.appName).append(";").append(h.picUrl).append(";").append(fmt.format(h.viewTime)).append(",");
        }

        SharedPreferences.Editor editor = context.getSharedPreferences("histories", Context.MODE_PRIVATE).edit();
        //步骤2-2：将获取过来的值放入文件
        editor.putString("histories", sb.toString());
        //步骤3：提交
        editor.commit();
    }

}
